'use strict';
const conn = require('../server/libs/Conn');
const utils = require('../server/libs/Utils');
const {createToken} = require('../server/libs/Token');


module.exports = async function (ctx) {
    let param = ctx.method === 'GET' ? ctx.query : ctx.request.fields;

    try {
        let loginName = param.loginName;
        let pwd = utils.encrypt(param.pwd);
        if (loginName && pwd) {
            let signInSql = 'SELECT * FROM user_file WHERE login_name = ? AND  password= ? ;SELECT * FROM user_group WHERE group_id in (SELECT group_id FROM user_file WHERE login_name = ? AND  password= ?) AND delete_sign = 1';
            let queryResult = await conn(signInSql, [loginName, pwd, loginName, pwd]),
                userInfo = queryResult[0].shift();
            if (!userInfo) {
                ctx.body = {success: false, message: '用户名或密码错误!'};
            } else {
                let token = createToken({user_id: userInfo.user_id});   //为登陆用户创建令牌
                userInfo.menus = eval(queryResult[1][0].sys_menu_id);
                ctx.body = {success: true, userInfo: userInfo, token: token};
            }
        } else {
            ctx.body = {success: false, message: '用户名或密码缺失'};
        }

    } catch (e) {
        ctx.body = {success: false, message: e.message};
    }

};
